package coms6111.astbbw;
import java.net.*;
import java.io.*;

//import sun.net.www.protocol.file.FileURLConnection;

/**
 *	A wrapper around the Yahoo BOSS query system: fetches XML data for a given set
 * 	of query terms (possibly with some restrictions) from BOSS.
 *
 * @author    Benjamin Warfield
 * @version   $Id: Class,v 1.1 2004/11/05 21:57:56 liyanage Exp $
 */
public class QueryFetcher {
	static final private String YAHOOID = "JAcfc9HIkY2GjpQ4i33DdD6imUDJGzOSTwV6gGXrVUwcUvroKiW6";
	private String appID;
	private String queryQuery; // The wages of a poorly thought-through naming convention
	private static String queryHost = "boss.yahooapis.com";
	private static String queryPathBase = "/ysearch/web/v1/";

	/**
	 * Constructor
	 * @param app_id_init the bbAuth appid for BOSS.
	 */
	public QueryFetcher(String app_id_init) {
		appID = app_id_init;
		queryQuery = "appid="+appID +"&format=xml"+"&abstract=long";
	}
	/**
	 * If a query should be site-restricted, this constructor should be used instead of the basic one.
	 * @param app_id_in The BOSS appID, as before.
	 * @param restrict_site the domain to which searches using this object should be restricted.
	 */
	public QueryFetcher(String app_id_in, String restrict_site) {
		this(app_id_in);
		try {
			queryQuery = queryQuery + "&sites=" + java.net.URLEncoder.encode(restrict_site, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			// this should never, ever happen
			throw new RuntimeException("apparently, utf8 is unsupported?");
		}
	}
	/**
	 * Main useful method: fire off a query to BOSS, and return the results.
	 * @param queryTerms a query string (e.g. "stephen colbert" or "tiger")
	 * @return a string containing the results, or null if something odd happened.
	 * @exception IOException in the case of a problem making the HTTP connection
	 * @exception URISyntaxException (this should never happen, actually.)
	 */

	public String runQuery(String queryTerms) throws IOException, URISyntaxException {
		URI queryURI = new URI(
			"http",				// scheme
			null,				// authority
			queryHost,  		// hostname
			-1,					// port (default)
			queryPathBase + queryTerms, // path
			queryQuery,			// query (?foo=bar&baz=whatsit)
			null);				// fragment
		URL queryURL = queryURI.toURL();
		HttpURLConnection conn = (HttpURLConnection) queryURL.openConnection();
		if ( 200 == conn.getResponseCode() ) {
			BufferedReader contentReader = new BufferedReader(
				new InputStreamReader( (InputStream) conn.getContent()));
			StringBuffer buff = new StringBuffer(4096); // pre-extend to a reasonable lenght
			String line = null;
			while (null != (line = contentReader.readLine())) {
				buff.append(line);
				buff.append("\n");
			}
			return buff.toString();
		} else {
			System.err.println("Connection to BOSS failed: " + conn.getResponseMessage());
			return null;
		}
	}


	/**
	 * Main method for command-line invocation (intended for debugging purposes).
	 *	Runs a query and prints out the text of the response to standard output.
	 * @param argv    the argument String array
	 */
	public static void main (String argv[]) {
		if ( 0 < argv.length ) {
			QueryFetcher fetch = new QueryFetcher(YAHOOID);
			String answer =null;
			try {
				answer = fetch.runQuery(argv[0]);
			} catch (Exception e) {
				System.err.print(e);
			}
			if (null != answer) {
				System.out.print(answer);
			}
		}
	}

}

